<template>
  <div class="answer-system">
    <!-- 连接状态指示 -->
    <div :class="['connection-status', connectionStatusClass]">
      {{ connectionStatusText }}
    </div>

    <!-- 管理员控制面板 -->
    <div v-if="isAdmin" class="admin-panel">
      <template v-if="false">
        <button @click="startAnswering" style="margin-right: 10px">开始抢答</button>
        <button @click="resetAnswering">重置</button>
      </template>
      <div style="margin-top: 20px">
        <van-button type="primary" @click="startAnswering" style="margin-right: 10px">开始抢答</van-button>
        <van-button type="primary" plain @click="resetAnswering">重置</van-button>
      </div>
    </div>

    <!-- 抢答按钮 -->
    <button
      @click="submitAnswer"
      :disabled="!canAnswer || !!firstResponder"
      class="answer-button"
    >
      {{ answerButtonText }}
    </button>

    <!-- 抢答结果 -->
    <div v-if="firstResponder" class="result-message">
      <template v-if="firstResponder === userId">
        恭喜！您抢答成功！
      </template>
      <template v-else>
        抢答成功者: {{ firstResponder }}
      </template>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: null,
      userId: `user_${Math.random().toString(36).substr(2, 6)}`,
      isAdmin: false,
      canAnswer: false,
      firstResponder: null,
      connectionStatus: 'disconnected', // disconnected/connecting/connected
      heartbeatInterval: null,
      reconnectInterval: null,
      reconnectAttempts: 0
    };
  },
  computed: {
    connectionStatusClass() {
      return {
        'disconnected': this.connectionStatus === 'disconnected',
        'connecting': this.connectionStatus === 'connecting',
        'connected': this.connectionStatus === 'connected'
      };
    },
    connectionStatusText() {
      const statusMap = {
        'disconnected': '连接已断开',
        'connecting': '连接中...',
        'connected': '已连接'
      };
      return statusMap[this.connectionStatus];
    },
    answerButtonText() {
      if (!this.canAnswer) return '等待抢答开始';
      if (this.firstResponder) return '抢答已结束';
      return '抢答';
    }
  },
  methods: {
    initWebSocket() {
      this.connectionStatus = 'connecting';
      this.ws = new WebSocket(`ws://${window.location.hostname}:5274`);

      // 连接成功
      this.ws.onopen = () => {
        this.connectionStatus = 'connected';
        this.reconnectAttempts = 0;
        this.startHeartbeat();
        this.registerUser();
      };

      // 接收消息
      this.ws.onmessage = (event) => {
        // 心跳响应
        if (event.data === 'pong') return;

        const data = JSON.parse(event.data);
        switch (data.type) {
          case 'status':
            this.canAnswer = data.status === '抢答开始';
            if (!this.canAnswer) this.firstResponder = null;
            break;
          case 'firstResponder':
            this.firstResponder = data.userId;
            break;
        }
      };

      // 连接关闭
      this.ws.onclose = () => {
        this.connectionStatus = 'disconnected';
        this.stopHeartbeat();
        this.attemptReconnect();
      };

      // 错误处理
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    },

    // 开始心跳检测
    startHeartbeat() {
      this.stopHeartbeat();
      this.heartbeatInterval = setInterval(() => {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send('ping');
        }
      }, 25000); // 25秒发送一次
    },

    // 停止心跳检测
    stopHeartbeat() {
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval);
        this.heartbeatInterval = null;
      }
    },

    // 尝试重新连接
    attemptReconnect() {
      if (this.reconnectInterval) return;

      this.reconnectInterval = setInterval(() => {
        if (this.reconnectAttempts >= 5) {
          this.stopReconnect();
          return;
        }

        this.reconnectAttempts++;
        console.log(`尝试第 ${this.reconnectAttempts} 次重连`);
        this.initWebSocket();
      }, 5000);
    },

    // 停止重连尝试
    stopReconnect() {
      if (this.reconnectInterval) {
        clearInterval(this.reconnectInterval);
        this.reconnectInterval = null;
      }
    },

    // 注册用户
    registerUser() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({
          type: 'register',
          userId: this.userId,
          isAdmin: this.isAdmin // 实际应用中应从登录信息获取
        }));
      }
    },

    // 提交抢答
    submitAnswer() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({
          type: 'answer',
          userId: this.userId
        }));
      }
    },

    // 管理员功能
    startAnswering() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({
          type: 'control',
          action: 'start'
        }));
      }
    },

    resetAnswering() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({
          type: 'control',
          action: 'reset'
        }));
      }
    }
  },
  mounted() {
    // 检查URL参数判断是否是管理员
    this.isAdmin = this.$route.query['admin'] === 'true'

    this.initWebSocket();

    // 页面可见性变化时重新连接
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible' &&
        this.connectionStatus === 'disconnected') {
        this.initWebSocket();
      }
    });
  },
  beforeUnmount() {
    this.stopHeartbeat();
    this.stopReconnect();
    if (this.ws) {
      this.ws.close();
    }
  }
};
</script>

<style scoped lang="scss">
.answer-system {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

.connection-status {
  padding: 5px 10px;
  border-radius: 4px;
  width: 160px;
  margin: 0 auto 15px;
}

.connected{
  background-color: #4CAF50;
  color: white;
}
.connecting{
  background-color: #FFC107;
  color: black;
}
.disconnected{
  background-color: #F44336;
  color: white;
}

.admin-panel {
  margin-bottom: 20px;
}

.answer-button {
  padding: 12px 24px;
  font-size: 18px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.answer-button:hover:not(:disabled) {
  background-color: #0b7dda;
}

.answer-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.result-message {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 16px;
}
</style>
